package cn.wolfcode.crm.web.filter;

import cn.wolfcode.crm.util.JSONResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

public class MyFormFilter extends FormAuthenticationFilter {
    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        response.setContentType("application/json;charset=UTF-8");
        //把json字符串输出到浏览器上
        response.getWriter().print(new ObjectMapper().writeValueAsString(new JSONResult()));
        //不需要执行后面的过滤器或者是Controller的方法
        return false;
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        //把异常信息打印出来
        e.printStackTrace();
        String errorMsg = "其他异常信息,请联系管理员!";
        //判断属于哪种异常,响应不同的错误信息给用户
        if(e instanceof UnknownAccountException){
            errorMsg = "用户名不存在!";
        }else if(e instanceof IncorrectCredentialsException){
            errorMsg = "密码错误!";
        }
        try {
            response.setContentType("application/json;charset=UTF-8");
            //response.setCharacterEncoding("utf-8");
            response.getWriter().print(new ObjectMapper().writeValueAsString(new JSONResult().mark(errorMsg)));
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return false;
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        //如果是login.do的请求,才会执行下面的逻辑
        if (isLoginRequest(request,response)) {
            //判断是否是已经登陆的状态,如果是就先注销再提交
            Subject subject = SecurityUtils.getSubject();
            if (subject.isAuthenticated()){
                subject.logout();
            }
        }
        return super.isAccessAllowed(request, response, mappedValue);
    }
}
